package dwl.graduation.design.service.impl;

import dwl.graduation.design.domain.Menu;
import dwl.graduation.design.domain.MenuExample;
import dwl.graduation.design.domain.MenuInsertRequest;
import dwl.graduation.design.domain.MenuUpdateRequest;
import dwl.graduation.design.mapper.MenuMapper;
import dwl.graduation.design.service.MenuService;
import dwl.graduation.design.utils.PageResult;
import dwl.graduation.design.utils.QueryPageBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public boolean updateMenu(MenuUpdateRequest menuUpdateRequest) {
        MenuExample menuExample = new MenuExample();
        menuExample.createCriteria().andIdEqualTo(menuUpdateRequest.getId());
        List<Menu> menus = menuMapper.selectByExample(menuExample);
        if (menus.size() == 0) {
            return false;
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuUpdateRequest,menu);
        MenuExample menuUpdateExample = new MenuExample();
        menuUpdateExample.createCriteria().andIdEqualTo(menu.getId());
        int falg = menuMapper.updateByExampleSelective(menu, menuUpdateExample);
        return falg > 0;
    }

    @Override
    public PageResult findMenuList(QueryPageBean queryPageBean) {
        if (!Objects.isNull(queryPageBean.getPageSize()) && !Objects.isNull(queryPageBean.getCurrentPage())) {
            queryPageBean.setCurrentPage((queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize());
        }
        List<Menu> menuList = menuMapper.getMenuList(queryPageBean);
        Long count = menuMapper.getListCount(queryPageBean);
        return PageResult.builder().rows(menuList).total(count).build();
    }

    @Override
    public boolean insertMenu(MenuInsertRequest request) {
        Menu menu = new Menu();
        BeanUtils.copyProperties(request, menu);
        int flag = menuMapper.insertSelective(menu);
        return flag > 0;
    }

    @Override
    public void deleteMenu(Integer id) {
        menuMapper.deleteByPrimaryKey(id);
    }
}
